package lib

import (
	"github.com/PuerkitoBio/goquery"
)

func Parse(r Ruler, target string) map[string][]string {
	result := make(map[string][]string)
	doc, _ := goquery.NewDocument(target)

	for key, value := range r.Rule() {
		if value.Selector == "" {
			continue
		}

		if doc.Find(value.Selector) == nil {
			continue
		}

		content := make([]string, doc.Find(value.Selector).Length())
		doc.Find(value.Selector).Each(func(i int, s *goquery.Selection) {
			if value.Attr == "" {
				content[i] = s.Text()
			} else {
				content[i], _ = s.Attr(value.Attr)
			}

			if value.Pipeline != nil {
				str := interface{}(content[i]).(string)
				content[i] = value.Pipeline(str).(string)
			}
		})
		result[key] = content
	}
	return result
}
